import { getList as getGoodList, goodCategory } from '@/api/good'
import { getList as bannerList } from '@/api/banner'
import { create as collectCreate, destroy as collectDestroy } from '@/api/collect'
import IDetail from '@/components/IDetail'

export default {
  components: {
    IDetail
  },
  data() {
    const validateRemark = (rule, value, callback) => {
      const flag = new RegExp("[`~!@#$^&*()=|{}':'\\[\\].<>《》/?~！@#￥……&*（）——|{}【】‘：”“'。？ ]")
      if (flag.test(value)) {
        return callback(new Error(this.$t('header.top.validate_remark')))
      } else {
        callback()
      }
    }
    return {
      specificationDefaultDisplay: {},
      navActive: -1,
      collect: false,
      categoryStyle: 0,
      naveOn: null,
      goodList: [],
      banner1: '',
      banner2: '', // 广告
      botadv: '',
      bannerList: [],
      categoryList: [],
      categorySublevel: [],
      recommendCategoryList: [],
      recommendGoodList: [],
      newGoodList: [],
      hotGoodList: [],
      searchRuleForm: {
        keyword: ''
      },
      navList: [{ name: this.$t('header.top.nav_list.home'), path: '/' }],
      cartActive: false,
      userActive: false,
      rules: {
        keyword: [{ validator: validateRemark, trigger: 'blur' }]
      }
    }
  },
  async asyncData(ctx) {
    try {
      let [goodData, bannerData, categoryData, newGoodData, hotGoodData] = await Promise.all([
        getGoodList({
          limit: 10,
          is_recommend: 1,
          sort: '-sort'
        }),
        bannerList({
          limit: 5,
          type: 0,
          state: 0,
          sort: '+sort'
        }),
        goodCategory({
          tree: true
        }),
        // goodCategory({
        //   is_recommend: 1
        // })
        getGoodList({
          limit: 10,
          is_new: 1,
          sort: '-sort'
        }),
        getGoodList({
          limit: 10,
          is_hot: 1,
          sort: '-sort'
        })
      ])
      bannerData.data.forEach(item => {
        item.url = item.url ? item.url.replace('?id=', '/') : ''
      })

      return {
        goodList: goodData.data,
        bannerList: bannerData.data,
        categoryList: categoryData,
        newGoodList: newGoodData.data,
        hotGoodList: hotGoodData.data

        // recommendCategoryList: recommendCategoryData
      }
    } catch (err) {
      ctx.$errorHandler(err)
    }
  },
  created() {
    this.categoryGood()
  },
  mounted() {
    this.setNavActive($nuxt.$route.path)
    this.getBanner()
  },
  methods: {
    toCollect(val) {
      console.log("🚀 ~  val: ", val)
      if (!$nuxt.$store.state.hasLogin) {
        $nuxt.$store.commit('loginCheck');
        return false
      }
      if (this.collect) {
        collectDestroy(val.id)
        // this.$message.success('取消成功')
      } else {
        collectCreate(val)
        this.$message.success('收藏成功')
      }
      this.collect = !this.collect
    },
    card(val) {
      console.log("🚀 ~  val: ", val)
      if (!$nuxt.$store.state.hasLogin) {
        $nuxt.$store.commit('loginCheck');
        return false
      }
      this.$refs.detail.initInfo(val)
    },
    setNavActive(path) {
      this.navActive = -1
      for (let i = 0; i < this.navList.length; i++) {
        if (this.navList[i].path.split('/')[1] === path.split('/')[1] || (this.$store.state.lang !== 'zh' && this.navList[i].path.split('/')[1] === path.split('/')[2])) {
          this.navActive = i
          break
        }
      }
    },
    userMenu() {
      this.userActive = true
    },
    userMenuOut() {
      this.userActive = false
    },
    // 搜索
    search() {
      this.$refs['searchRuleForm'].validate(valid => {
        if (valid) {
          this.$router.push({
            path: `/product/list`,
            query: { title: this.searchRuleForm.keyword }
          })
        }
      })
    },
    // 分类切换
    naveCut(index) {
      if (index !== -1) {
        this.naveOn = index
        if (this.categoryList[index].children) {
          //存在子类目
          if (this.categoryList[index].children[0].resources) {
            this.categorySublevel = this.categoryList[index].children
            this.categoryStyle = 2
          } else {
            //存在三级
            this.categorySublevel = this.categoryList[index].children
            this.categoryStyle = 1
          }
        } else {
          this.categorySublevel = []
        }
      }
    },
    // 获取分类商品
    categoryGood() {
      // this.recommendCategoryList.forEach((item, index) => {
      // this.recommendGoodList[index]  = []
      getGoodList({
        limit: 100,
        category_id: ''
      }).then(response => {
        this.recommendGoodList = response.data
        // console.log('🚀 ~  this.recommendGoodList: ', this.recommendGoodList)

        // this.$forceUpdate()
      })
      // })
    },
    // 分类移出
    naveShiftOut() {
      this.naveOn = null
      this.categoryStyle = 0
    },
    // 首页广告
    getBanner() {
      bannerList({
        limit: 1,
        type: 10,
        state: 0,
        sort: '+sort'
      }).then(response => {
        this.banner1 = response.data[0]
        if (this.banner1) {
          this.banner1.url = this.banner1.url ? this.banner1.url.replace('?id=', '/') : ''
        }
      })
      bannerList({
        limit: 1,
        type: 11,
        state: 0,
        sort: '+sort'
      }).then(response => {
        this.banner2 = response.data[0]
        if (this.banner2) {
          this.banner2.url = this.banner2.url ? this.banner2.url.replace('?id=', '/') : ''
        }
      })
      bannerList({
        limit: 1,
        type: 12,
        state: 0,
        sort: '+sort'
      }).then(response => {
        this.botadv = response.data[0]
        if (this.botadv) {
          this.botadv.url = this.botadv.url ? this.botadv.url.replace('?id=', '/') : ''
        }
      })
    }
  }
}
